<?php
spl_autoload_register('auto_load');
#自动调用
function auto_load($class){
	if (empty($class)) {
		return false;
	}
	static $loadfile=array();
	$file=DOCUMENT_MODEL.'/'.$class.'.php';
	if(!empty($loadfile[hash('crc32',$file)])){
		return true;//已经有加载过此文件
	}
	if (file_exists($file)) {
		require_once($file);
		$loadfile[hash('crc32',$file)]=true;
	}
}
#取得系统配置
function get_config($key=null){
	static $config=array();
	if(!empty($config[hash('crc32',$key)])){
		return $config[hash('crc32',$key)];
	}
	require_once(DOCUMENT_ROOT.'/config.php');
	$file=new config();
	if($key===null){
		return $file;
	}
	if (isset($file->$key)){
		$config[hash('crc32',$key)]=$file->$key;
		return $config[hash('crc32',$key)];
	}else{
		return $file;
	}
}
#取得数据库连接
function get_db($config='default'){
	static $db=array();
	if(empty($db[hash('crc32',$config)])){
		$db_config=get_config('db_config');
		if (is_array($db_config[$config])) {
			$db_type=strtoupper(get_config('connect_type'));
			if($db_type=='PDO'){
				load('libraries.DB.pdo_mysql');
				$db[hash('crc32',$config)]=pdo_mysql::get_connect($db_config[$config]);
			}else{
				load('libraries.DB.mysql');
				$db[hash('crc32',$config)]=mysql::get_connect($db_config[$config]);
			}
			return $db[hash('crc32',$config)];
		}else{
			return false;
		}
	}
	return $db[hash('crc32',$config)];
}
#错误提示
function error_box($error = '', $gotourl = '(-1)', $time = 3 ) {
	if ($gotourl==='(-1)' || $gotourl==='-1') {
		$gotourl_js = 'history.go(-1)';
		$gotourl = 'javascript:history.go(-1)';
	} elseif($gotourl==='window.close' || $gotourl==='window.close()' || $gotourl==='close'  || $gotourl==='close()' ) {
		$gotourl = 'javascript:window.close()';
		$gotourl_js='window.close()';
	}else{
		$gotourl_js = ((('' . 'self.location.href=\'') . $gotourl) . '\';');
	}
	$file = DOCUMENT_LIBRARIES.DS.'core'.DS.'errormsg.php';
	if (file_exists($file)) {
		include ($file);
		exit();
	} 
}
#加载文件
function load($file){
	$file=DOCUMENT_ROOT.DS.str_replace('.',DS,$file).'.php';
	#debug($file);
	if (file_exists($file)) {
		include_once($file);
		return true;
	}
	return false;
}
#取得js文件
function get_js($file){
	$url_rewrite=&get_config('url_rewrite');
	if ($url_rewrite) {
		$js=$_COOKIE['theme'].DS.'js/'.$file.'.js';
	}
	return $js;
}
#加载module模块
function module($module_name){
	static $module=array();
	$key_name=hash('crc32',$module_name);
	$file=DOCUMENT_MODULE.DS.$module_name.'.php';
	if(empty($module[$key_name])){
		if (!file_exists($file)) {
			error_box('找定的方法找不到！！请联系管理员！！');
		}
		require_once(DOCUMENT_MODULE.DS.$module_name.'.php');
		$class_name='module_'.$module_name;
		$module[$key_name]=new  $class_name ();
	}
	return $module[$key_name];
}
#加载libraries部份公用功能
function lib($lib_name,$parm=null){
	static $lib=array();
	$key_name=hash('crc32',$lib_name);
	if(empty($lib[$key_name])){
		$file=DOCUMENT_LIBRARIES.DS.'class'.DS.$lib_name.'.php';
		if (!file_exists($file)) {
			die('找不到公用模块'.$lib_name);
		}
		require_once($file);
		$class_name='module_'.$module_name;
		$lib[$key_name]=new  $lib_name ($parm);
	}
	return $lib[$key_name];
}
#取得当前用户的IP
function getIP (){
	global $_SERVER;
	if (getenv('HTTP_CLIENT_IP')) {
		$ip = getenv('HTTP_CLIENT_IP');
	} else if (getenv('HTTP_X_FORWARDED_FOR')) {
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	} else if (getenv('REMOTE_ADDR')) {
		$ip = getenv('REMOTE_ADDR');
	} else {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}
#取得提示语言包
function get_language(){
	static $language_package;
	if(empty($language_package)){
		if (!empty($_COOKIE['theme'])) {
			$theme=$_COOKIE['theme'];
		}else{
			$theme=&get_config('theme');
		}
		$file=DOCUMENT_ROOT.DS.'language'.DS.$theme.'.php';
		if (file_exists($file)) {
			require_once($file);
		}
		$language_package=$msg_language;
	}
	return $language_package;
}
#加载json部份
function get_json(){
	static $json;
	if(empty($json)){
		require_once(DOCUMENT_LIBRARIES.'/class/JSON.php');
		$json=new Services_JSON();
	}
	return $json;
}
#取得时间,如果有传递老时间，肯算出共用了多少时间
function getmicrotime($old_time=null){ 
    list($usec, $sec) = explode(" ",microtime()); 
    if(is_null($old_time)){
    	return ((float)$usec + (float)$sec);
    }else{
    	return ((float)$usec + (float)$sec)-$old_time;
    }
}
/**
 * author:iceboy
 * date:2009-03-25
 * module:删除文件，此文件无返回值
 */
function del_file($file){
	if (file_exists($file)) {
		unlink($file);
	}
}

#取得当前的模版文件
function get_theme(){
	debug($_COOKIE);
	if(!isset($_COOKIE['theme'])){
		setcookie('theme',get_config('theme'),time()+30000);
	}
	return $_COOKIE['theme'];
}
/**
 * @author iceboy
 * @date 2009-09-13
 * @todo 解析URL的参数，生成数组
 * @return unknown
 */
function par_url(){
    $url=$_GET[get_config('url_var')];
    $url=explode('/',$url);
    return $url;
}
/**
 * @author iceboy
 * @todo 重写生成URL部份的方法，支持新的URLREWRITE
 * @param unknown_type $array 生成方法的数组
 * @return unknown 生成好的URL
 */
function get_url($array){
	$url_rewrite=&get_config('url_rewrite');
	if(!empty($array['a']) && !empty($array['m'])){
		if ($url_rewrite) {
			#如果打开了url_rewrite
			$url='/'.$array['m'].'/'.$array['a'];
		}else{
			#如果没有打开url_rewrite
			$url='/index.php?m='.$array['m'].'&a='.$array['a'];
		}
		unset($array['a'],$array['m']);
		if (count($array)>0) {
			foreach ($array as $key=>$value){
				if ($url_rewrite) {
					$url.='/'.$value;
				}else{
					$url.='&'.$key.'='.$value;
				}
			}
		}
		return $url;
	}else{
		exit('取得URL错误！');
	}
}
/**
 * @author shenjun
 * @todo 系统调试参数
 */
function debug(){
	$trace=debug_backtrace();
	$args = func_get_args();
	new debug($args,$trace);
}
/**
 * @author shenjun
 * @todo 框架的一些版权信息
 */
function copyright(){
	$time=sprintf('%.6f',getmicrotime(DOCUMENT_BEGIN_TIME));
	$memory=memory_get_peak_usage();
	$memory=sprintf('%.6f',$memory/1024/1024);
	echo '<div id="blueice_copyright" style="color:#CCCCCC;">Powered by <a href="http://www.sziwap.com" target="_blank">blueice</a>! Parse Time:'.$time.'s!Use memory:'.$memory.'mb! </div>';
}

function get_nav($nav='head'){
	load('view.nav.'.$nav);
}
/**
 * 重定向，$url为空，返回上一级;
 *
 * @param string $url 地址
 * @param int $time  重定向时间
 * @param bool $js   指定用JS重定向
 */
!session_start() && session_start();
function gourl($url='',$time=0,$js=false){
	$url=empty($url)?$_SERVER['HTTP_REFERER']:$url;
	if(!$js){
		if(headers_sent() || $time>0){
			echo <<<HTML
		<html>      
        <head>      
        <meta http-equiv="refresh" content="{$time};URL={$url}" />      
        </head>      
        </html> 
HTML;
	exit();
		}else {
			header("Location: {$url}");
			exit();
		}
	}
	
	$jshtml = '<script language="JavaScript" type="text/javascript">'; 
    $url = rawurlencode($url);      
     if ($time> 0) {      
         $jshtml .= "window.setTimeOut(function () { document.location='{$url}'; }, {$time});";      
     } else {      
         $jshtml .= "document.location='{$url}';";      
     }
     echo $jshtml;
     exit();  	
}

/**
 * @param $name 隐藏字段名
 * @param $value 隐藏字段值
 * @param $toolbar 工具栏样式,可选值 Basic Default
 * @param $skin 面板,可选值 default office2003 silver
 * @param $Lang 语言,可选值 zh-cn zh e
 *
 */
function htmlEdit($name,$value='',$height=420,$width=720,$toolbar='Default',$skin='office2003',$Lang='en'){
	load('www.extend.FCKeditor.fckeditor');
	$Lang=get_theme();
	$sBasePath = "/extend/FCKeditor/";
	$oFCKeditor = new FCKeditor($name) ;
	$oFCKeditor->BasePath = $sBasePath ;
	if($Lang) 		$oFCKeditor->Config['AutoDetectLanguage'] = false ;
	if($Lang) 		$oFCKeditor->Config['DefaultLanguage'] = $Lang ;
	if($skin) 		$oFCKeditor->Config['SkinPath'] = $sBasePath . 'editor/skins/'.$skin.'/' ;
	if($toolbar)	$oFCKeditor->ToolbarSet = $toolbar ;
	if($width) 		$oFCKeditor->Width = $width ;
	if($height) 	$oFCKeditor->Height = $height ;
	$oFCKeditor->Value = $value ;
	return $oFCKeditor->CreateHtml() ;
}

function price_format($price,$type=true,$num=2){
	if($type){
		$price=$price/100;
	}else{
		$price=$price;
	}
	$price=abs($price);
	$price=number_format($price,2);
	return $price;
}

function get_ip() {
	global $_SERVER;
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
	   $onlineip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
	   $onlineip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
	   $onlineip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
	   $onlineip = $_SERVER['REMOTE_ADDR'];
	}
	$onlineip = preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
	return $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
}
?>